package com.mytest.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.mytest.annotation.LoginRequired;
import com.mytest.jwtentity.JWTResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @author Wulc
 * @date 2024/4/7 17:56
 * @description
 */
public class AuthorityInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    @Qualifier("redisTemplate1")
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //return super.preHandle(request, response, handler);
        String path = request.getServletPath();
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // ①:START 方法注解级拦截器
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 判断接口是否需要登录
        LoginRequired methodmethodAnnotation = method.getAnnotation(LoginRequired.class);
        // 有 @LoginRequired 注解，需要认证
        if (methodmethodAnnotation != null) {
            // 这写你拦截需要干的事儿，比如取缓存，SESSION，权限判断等
            System.out.println("触发了注解拦截器：" + path);
            System.out.println("request=" + request);
            System.out.println("token=" + request.getHeader("Authorization"));
            System.out.println("username=" + request.getParameter("username"));
            String username = request.getParameter("username");
            String bearToken = request.getHeader("Authorization");
            String token = bearToken.substring(7, bearToken.length());
            String loginToken = "";
            if (redisTemplate.opsForValue().get(username) == null) {
                System.out.println("用户未登录");
                //response.setContentType("用户未登录");
                return false;
            }
            loginToken = redisTemplate.opsForValue().get(username).toString();
            if (token.equals(loginToken)) {
                //returnJson(response, JSONObject.toJSONString(new JWTResponseData(200, "已登录", "用户已登录", loginToken)));
                return true;
            } else {
                System.out.println("用户未登录");
                //response.setContentType("用户未登录");
                returnJson(response, JSONObject.toJSONString(new JWTResponseData(401, "未登录", "用户未登录", "")));
                return false;
            }
            //JWTResult result = JWTUtils.validateJWT(token);

//            if (result.isSuccess()) {
//                return true;
//            } else {
//                System.out.println("用户未登录");
//                return false;
//            }
        }
        //response.setContentType("用户已登录");
        return true;
    }

    private void returnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            //logger.error("response error", e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

}
